library IEEE;
use IEEE.STD_LOGIC_1164.ALL;
use work.faw_types.all;


entity Counters is
    Port ( clk_c : in  STD_LOGIC;
				reset_c : in STD_LOGIC;
           pixel_valid_c : in  STD_LOGIC;
           line_valid_c : in  STD_LOGIC;
			  frame_valid_c : in STD_LOGIC;
			  i_c : out COUNTER_ROWS;
			  j_c : out COUNTER_COLUMNS);
end Counters;

architecture Behavioral of Counters is

	
begin

	processo: process(clk_c,frame_valid_c,line_valid_c)
	
	variable ROWS_COUNTER: COUNTER_ROWS:= 0;
	variable COLUMNS_COUNTER: COUNTER_COLUMNS:= 0;
	
	begin
		if(frame_valid_c'event and frame_valid_c='1' and clk_c='1')then
			ROWS_COUNTER:=0;
			COLUMNS_COUNTER:=0;
		end if;
		if(line_valid_c'event and line_valid_c='0' and clk_c='1' and frame_valid_c='1')then
			COLUMNS_COUNTER:=0;
		end if;
		if(line_valid_c'event and line_valid_c='1' and clk_c='1' and frame_valid_c='1')then
			COLUMNS_COUNTER:=1;
			ROWS_COUNTER:=ROWS_COUNTER+1;
		end if;
		
		--patch per la commutazione "involontaria" di i dopo la caduta di linevalid.
		--se non lo si facesse commutare proprio sarebbe meglio, magari bisogna capire cosa lo fa commutare
--		if(line_valid_c'event and line_valid_c='0' and frame_valid_c='1') then 
--			COLUMNS_COUNTER:=COLUMNS_COUNTER-1;
--		end if;
	
		if (clk_c'event and clk_c='1') then
			
			if(reset_c='1')then
				ROWS_COUNTER:=0;
				COLUMNS_COUNTER:=0;
			end if;
			
			if (frame_valid_c='1')then
				if (line_valid_c='1' and pixel_valid_c='1') then
					COLUMNS_COUNTER:=COLUMNS_COUNTER+1;
				end if;
			end if;
		end if;
		
		i_c<=ROWS_COUNTER;
		j_c<=COLUMNS_COUNTER;
	
	
	end process processo;


end Behavioral;

